<template>
  <view class="role-container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 页面标题 -->
    <view class="page-header">
      <view class="title-section">
        <text class="page-title">角色管理</text>
        <text class="date">{{ currentDate }}</text>
      </view>
      <view class="refresh-btn" @click="refreshData">
        <uni-icons type="refresh" size="18" color="#FF8C42"></uni-icons>
      </view>
    </view>

    <!-- 角色统计概览 -->
    <view class="stats-overview">
      <view class="stats-grid">
        <!-- 角色总数 -->
        <view class="stat-card">
          <view class="stat-icon role-icon">
            <uni-icons type="gear" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">角色总数</text>
            <text class="stat-value">{{ roleStats.totalRoles }}</text>
          </view>
        </view>
        
        <!-- 启用角色 -->
        <view class="stat-card">
          <view class="stat-icon active-icon">
            <uni-icons type="checkmarkempty" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">启用角色</text>
            <text class="stat-value">{{ roleStats.activeRoles }}</text>
          </view>
        </view>
        
        <!-- 今日新增 -->
        <view class="stat-card">
          <view class="stat-icon new-icon">
            <uni-icons type="plus" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">今日新增</text>
            <text class="stat-value">{{ roleStats.todayNewRoles }}</text>
          </view>
        </view>
        
        <!-- 已停用 -->
        <view class="stat-card">
          <view class="stat-icon disabled-icon">
            <uni-icons type="close" size="24" color="#FF8C42"></uni-icons>
          </view>
          <view class="stat-content">
            <text class="stat-label">已停用</text>
            <text class="stat-value">{{ roleStats.disabledRoles }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 操作按钮区域 -->
    <view class="action-bar">
      <view class="search-box">
        <uni-icons type="search" size="16" color="#999"></uni-icons>
        <input 
          type="text" 
          v-model="searchKeyword" 
          placeholder="搜索角色名称" 
          confirm-type="search"
          @confirm="searchRoles"
          @input="onSearchInput"
        />
        <view v-if="searchKeyword" class="clear-search" @click="clearSearch">
          <uni-icons type="close" size="14" color="#999"></uni-icons>
        </view>
      </view>
      <!-- <view class="filter-btn" @click="showFilterOptions">
        <uni-icons type="filter" size="20" color="#666"></uni-icons>
        <text class="filter-text">筛选</text>
      </view> -->
      <view class="add-btn" @click="showAddRoleForm">
        <uni-icons type="plus" size="20" color="#FFFFFF"></uni-icons>
        <text>创建角色</text>
      </view>
    </view>
    
    <!-- 状态标签 -->
    <view class="status-tabs">
      <scroll-view scroll-x="true" class="status-scroll" show-scrollbar="false">
        <view class="status-list">
          <view 
            v-for="(status, index) in roleStatuses" 
            :key="index"
            :class="['status-item', selectedStatus === status.value ? 'status-active' : '']"
            @click="selectStatus(status.value)"
          >
            {{ status.name }}
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 角色列表 -->
    <view class="role-list">
      <view 
        v-for="role in displayRoles" 
        :key="role.id" 
        class="role-card"
        :class="{'disabled-role': role.status !== 1}"
      >
        <view class="role-header">
          <view class="role-icon-section">
            <view class="role-icon-wrapper">
              <uni-icons type="gear" size="32" color="#FF8C42"></uni-icons>
            </view>
            <view v-if="role.status !== 1" class="disabled-badge">已停用</view>
          </view>
          <view class="role-info">
            <text class="role-name">{{ role.name }}</text>
            <text class="role-code">编码: {{ role.code }}</text>
            <text class="role-description">{{ role.description || '暂无描述' }}</text>
          </view>
          <view class="role-status" :class="getStatusClass(role.status)">
            {{ getStatusText(role.status) }}
          </view>
        </view>
        
        <view class="role-details">
          <view class="detail-item">
            <text class="detail-label">角色ID:</text>
            <text class="detail-value">{{ role.id }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间:</text>
            <text class="detail-value">{{ formatDate(role.createTime) }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">更新时间:</text>
            <text class="detail-value">{{ formatDate(role.updateTime) }}</text>
          </view>
        </view>
        
        <view class="role-actions">
          <view class="action-btn view-btn" @click="viewRolePermissions(role.id)">
            <uni-icons type="eye" size="16" color="#FF8C42"></uni-icons>
            <text>查看权限</text>
          </view>
          <view class="action-btn permission-btn" @click="assignPermissions(role)">
            <uni-icons type="gear" size="16" color="#10B981"></uni-icons>
            <text>分配权限</text>
          </view>
          <view 
            class="action-btn status-btn" 
            :class="role.status === 1 ? 'disable-btn' : 'enable-btn'"
            @click="toggleRoleStatus(role)"
          >
            <uni-icons :type="role.status === 1 ? 'close' : 'checkmarkempty'" size="16" :color="role.status === 1 ? '#666' : '#10B981'"></uni-icons>
            <text>{{ role.status === 1 ? '停用' : '启用' }}</text>
          </view>
          <view class="action-btn edit-btn" @click="editRole(role)">
            <uni-icons type="edit" size="16" color="#666"></uni-icons>
            <text>编辑</text>
          </view>
        </view>
      </view>
      
      <!-- 加载中状态 -->
      <view v-if="isLoading" class="loading-state">
        <uni-icons type="spinner-cycle" size="30" color="#FF8C42"></uni-icons>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!isLoading && displayRoles.length === 0" class="empty-state">
        <image class="empty-image" src="/static/empty-role.png"></image>
        <text class="empty-text">{{ searchKeyword ? '未找到相关角色' : '暂无角色数据' }}</text>
        <view class="empty-action" @click="showAddRoleForm">创建角色</view>
      </view>
    </view>
    
    <!-- 分页控制 -->
    <view v-if="totalPages > 1" class="pagination">
      <view 
        class="pagination-btn prev-btn" 
        :class="{ 'disabled': currentPage === 1 }"
        @click="prevPage"
      >
        <uni-icons type="left" size="14" :color="currentPage === 1 ? '#ccc' : '#666'"></uni-icons>
        <text>上一页</text>
      </view>
      <view class="pagination-info">{{ currentPage }} / {{ totalPages }}</view>
      <view 
        class="pagination-btn next-btn" 
        :class="{ 'disabled': currentPage === totalPages }"
        @click="nextPage"
      >
        <text>下一页</text>
        <uni-icons type="right" size="14" :color="currentPage === totalPages ? '#ccc' : '#666'"></uni-icons>
      </view>
    </view>
    
    <!-- 角色编辑弹窗 -->
    <view v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
      <view class="edit-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ isEditMode ? '编辑角色' : '创建角色' }}</text>
          <view class="modal-close" @click="closeEditModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">角色名称</text>
            <input 
              class="form-input" 
              v-model="editingRole.name" 
              placeholder="请输入角色名称"
            />
          </view>
          <view class="form-item">
            <text class="form-label">角色编码</text>
            <input 
              class="form-input" 
              v-model="editingRole.code" 
              placeholder="请输入角色编码"
              :disabled="isEditMode"
            />
          </view>
          <view class="form-item">
            <text class="form-label">角色描述</text>
            <textarea 
              class="form-textarea" 
              v-model="editingRole.description" 
              placeholder="请输入角色描述"
            />
          </view>
          <view class="form-item">
            <text class="form-label">状态</text>
            <view class="status-selector">
              <view 
                class="status-option" 
                :class="{ 'active': editingRole.status === 1 }"
                @click="editingRole.status = 1"
              >
                启用
              </view>
              <view 
                class="status-option" 
                :class="{ 'active': editingRole.status === 0 }"
                @click="editingRole.status = 0"
              >
                停用
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closeEditModal">取消</view>
          <view class="confirm-btn" @click="saveRole">保存</view>
        </view>
      </view>
    </view>
    
    <!-- 权限分配弹窗 -->
    <view v-if="showPermissionModal" class="modal-overlay" @click="closePermissionModal">
      <view class="permission-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">分配权限 - {{ currentRole?.name }}</text>
          <view class="modal-close" @click="closePermissionModal">
            <uni-icons type="close" size="20" color="#666"></uni-icons>
          </view>
        </view>
        <view class="modal-body">
          <view class="permission-list">
            <view 
              v-for="permission in availablePermissions" 
              :key="permission.id"
              class="permission-item"
              @click="togglePermission(permission.id)"
            >
              <view class="permission-checkbox" :class="{ 'checked': selectedPermissions.includes(permission.id) }">
                <uni-icons v-if="selectedPermissions.includes(permission.id)" type="checkmarkempty" size="16" color="#FFFFFF"></uni-icons>
              </view>
              <view class="permission-info">
                <text class="permission-name">{{ permission.name }}</text>
                <text class="permission-description">{{ permission.description }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="cancel-btn" @click="closePermissionModal">取消</view>
          <view class="confirm-btn" @click="savePermissions">保存权限</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
//import uni from '@dcloudio/uni-app'

// 模拟角色数据
const mockRoles = [
  {
    id: 1,
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    description: '拥有系统所有权限，可以管理所有功能模块',
    status: 1,
    createTime: '2024-01-15T10:30:00',
    updateTime: '2024-01-20T14:20:00'
  },
  {
    id: 2,
    name: '系统管理员',
    code: 'SYSTEM_ADMIN',
    description: '负责系统配置和用户管理，拥有大部分管理权限',
    status: 1,
    createTime: '2024-01-16T09:15:00',
    updateTime: '2024-01-22T16:45:00'
  },
  {
    id: 3,
    name: '业务管理员',
    code: 'BUSINESS_ADMIN',
    description: '负责业务数据管理，包括商品、订单等业务功能',
    status: 1,
    createTime: '2024-01-18T11:20:00',
    updateTime: '2024-01-25T13:30:00'
  },
  {
    id: 4,
    name: '客服专员',
    code: 'CUSTOMER_SERVICE',
    description: '负责客户服务相关功能，处理用户咨询和投诉',
    status: 1,
    createTime: '2024-01-20T08:45:00',
    updateTime: '2024-01-26T10:15:00'
  },
  {
    id: 5,
    name: '财务专员',
    code: 'FINANCE_STAFF',
    description: '负责财务相关功能，包括订单结算、财务报表等',
    status: 0,
    createTime: '2024-01-22T14:30:00',
    updateTime: '2024-01-28T09:20:00'
  },
  {
    id: 6,
    name: '运营专员',
    code: 'OPERATION_STAFF',
    description: '负责运营活动管理，包括促销活动、内容管理等',
    status: 1,
    createTime: '2024-01-25T16:10:00',
    updateTime: '2024-01-29T11:40:00'
  },
  {
    id: 7,
    name: '数据分析师',
    code: 'DATA_ANALYST',
    description: '负责数据分析和报表生成，只读权限',
    status: 1,
    createTime: '2024-01-28T13:25:00',
    updateTime: '2024-01-30T15:50:00'
  },
  {
    id: 8,
    name: '测试专员',
    code: 'TEST_STAFF',
    description: '负责系统测试，临时角色',
    status: 0,
    createTime: '2024-01-30T10:00:00',
    updateTime: '2024-01-30T10:00:00'
  }
]

// 模拟权限数据
const mockPermissions = [
  { id: 1, name: '用户管理', description: '管理系统用户，包括创建、编辑、删除用户' },
  { id: 2, name: '角色管理', description: '管理系统角色，包括角色权限分配' },
  { id: 3, name: '权限管理', description: '管理系统权限，配置功能访问控制' },
  { id: 4, name: '商品管理', description: '管理商品信息，包括商品上架、下架、编辑' },
  { id: 5, name: '订单管理', description: '管理订单信息，处理订单状态变更' },
  { id: 6, name: '财务管理', description: '管理财务数据，查看财务报表' },
  { id: 7, name: '客服管理', description: '管理客服功能，处理客户咨询' },
  { id: 8, name: '运营管理', description: '管理运营活动，配置促销活动' },
  { id: 9, name: '数据分析', description: '查看数据报表，进行数据分析' },
  { id: 10, name: '系统设置', description: '配置系统参数，管理系统设置' }
]

// 模拟角色权限关系
const mockRolePermissions = {
  1: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], // 超级管理员拥有所有权限
  2: [1, 2, 3, 10], // 系统管理员
  3: [4, 5, 8], // 业务管理员
  4: [7], // 客服专员
  5: [6], // 财务专员
  6: [8, 9], // 运营专员
  7: [9], // 数据分析师
  8: [] // 测试专员
}

// 基础数据
const statusBarHeight = ref(0)
const searchKeyword = ref('')
const selectedStatus = ref('all')
const allRoles = ref([...mockRoles])
const isLoading = ref(false)
const showEditModal = ref(false)
const showPermissionModal = ref(false)
const isEditMode = ref(false)
const currentRole = ref(null)
const availablePermissions = ref([...mockPermissions])
const selectedPermissions = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalRecords = ref(0)

// 编辑角色数据
const editingRole = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 1
})

// 角色统计数据
const roleStats = reactive({
  totalRoles: 0,
  activeRoles: 0,
  todayNewRoles: 0,
  disabledRoles: 0
})

// 角色状态
const roleStatuses = [
  { value: 'all', name: '全部' },
  { value: 1, name: '启用' },
  { value: 0, name: '停用' }
]

// 获取当前日期
const currentDate = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1
  const day = now.getDate()
  return `${year}年${month}月${day}日`
})

// 当前页显示的角色
const displayRoles = computed(() => {
  let filteredRoles = [...allRoles.value]
  
  // 状态筛选
  if (selectedStatus.value !== 'all') {
    filteredRoles = filteredRoles.filter(role => role.status === selectedStatus.value)
  }
  
  // 搜索筛选
  if (searchKeyword.value) {
    filteredRoles = filteredRoles.filter(role => 
      role.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      role.code.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  // 更新总记录数和总页数
  totalRecords.value = filteredRoles.length
  totalPages.value = Math.ceil(filteredRoles.length / pageSize.value)
  
  return filteredRoles.slice(start, end)
})

// 获取状态栏高度
const getStatusBarHeight = () => {
  try {
    const systemInfo = uni.getSystemInfoSync()
    statusBarHeight.value = systemInfo.statusBarHeight || 0
  } catch (e) {
    console.error('获取系统信息失败:', e)
    statusBarHeight.value = 0
  }
}

// 模拟获取角色数据
const fetchRoles = async () => {
  isLoading.value = true
  
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  updateRoleStats()
  isLoading.value = false
}

// 模拟获取角色权限
const fetchRolePermissions = async (roleId) => {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  return mockRolePermissions[roleId] || []
}

// 更新角色统计数据
const updateRoleStats = () => {
  roleStats.totalRoles = allRoles.value.length
  roleStats.activeRoles = allRoles.value.filter(r => r.status === 1).length
  roleStats.disabledRoles = allRoles.value.filter(r => r.status !== 1).length
  
  // 今日新增（模拟今天创建的角色）
  const today = new Date().toDateString()
  roleStats.todayNewRoles = allRoles.value.filter(r => {
    if (!r.createTime) return false
    return new Date(r.createTime).toDateString() === today
  }).length
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已停用',
    1: '启用'
  }
  return statusMap[status] || '未知'
}

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-disabled',
    1: 'status-normal'
  }
  return classMap[status] || ''
}

// 重置编辑表单
const resetEditingRole = () => {
  Object.assign(editingRole, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: 1
  })
}

// 刷新数据
const refreshData = async () => {
  try {
    uni.showLoading({ title: '刷新中...' })
    await fetchRoles()
    uni.showToast({
      title: '数据已刷新',
      icon: 'success'
    })
  } catch (error) {
    uni.showToast({
      title: '刷新失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 选择状态
const selectStatus = (status) => {
  selectedStatus.value = status
  currentPage.value = 1
}

// 搜索输入事件
const onSearchInput = () => {
  if (searchKeyword.value === '') {
    currentPage.value = 1
  }
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  currentPage.value = 1
}

// 搜索角色
const searchRoles = () => {
  currentPage.value = 1
}

// 显示筛选选项
// const showFilterOptions = () => {
//   uni.showActionSheet({
//     itemList: ['按创建时间排序', '按更新时间排序', '按状态排序'],
//     success: (res) => {
//       uni.showToast({
//         title: '筛选功能开发中',
//         icon: 'none'
//       })
//     }
//   })
// }

// 显示添加角色表单
const showAddRoleForm = () => {
  isEditMode.value = false
  resetEditingRole()
  showEditModal.value = true
}

// 查看角色权限
const viewRolePermissions = async (roleId) => {
  try {
    const permissions = await fetchRolePermissions(roleId)
    const permissionNames = permissions.map(id => {
      const permission = mockPermissions.find(p => p.id === id)
      return permission ? permission.name : ''
    }).filter(name => name).join('、')
    
    uni.showModal({
      title: '角色权限',
      content: `该角色拥有 ${permissions.length} 个权限：${permissionNames || '暂无权限'}`,
      showCancel: false
    })
  } catch (error) {
    uni.showToast({
      title: '获取权限失败',
      icon: 'none'
    })
  }
}

// 分配权限
const assignPermissions = async (role) => {
  currentRole.value = role
  
  try {
    // 获取当前角色的权限
    const currentPermissions = await fetchRolePermissions(role.id)
    selectedPermissions.value = currentPermissions
    showPermissionModal.value = true
  } catch (error) {
    uni.showToast({
      title: '获取角色权限失败',
      icon: 'none'
    })
  }
}

// 切换权限选择
const togglePermission = (permissionId) => {
  const index = selectedPermissions.value.indexOf(permissionId)
  if (index > -1) {
    selectedPermissions.value.splice(index, 1)
  } else {
    selectedPermissions.value.push(permissionId)
  }
}

// 保存权限分配
const savePermissions = async () => {
  if (!currentRole.value) return
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 更新模拟数据
    mockRolePermissions[currentRole.value.id] = [...selectedPermissions.value]
    
    uni.showToast({
      title: '权限分配成功',
      icon: 'success'
    })
    closePermissionModal()
  } catch (error) {
    uni.showToast({
      title: '权限分配失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 切换角色状态
const toggleRoleStatus = async (role) => {
  const newStatus = role.status === 1 ? 0 : 1
  
  uni.showModal({
    title: '确认操作',
    content: `确定要${newStatus === 1 ? '启用' : '停用'}角色"${role.name}"吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '处理中...' })
          
          // 模拟网络延迟
          await new Promise(resolve => setTimeout(resolve, 500))
          
          // 更新角色状态
          const roleIndex = allRoles.value.findIndex(r => r.id === role.id)
          if (roleIndex !== -1) {
            allRoles.value[roleIndex].status = newStatus
            allRoles.value[roleIndex].updateTime = new Date().toISOString()
          }
          
          updateRoleStats()
          
          uni.showToast({
            title: `角色已${newStatus === 1 ? '启用' : '停用'}`,
            icon: 'success'
          })
        } catch (error) {
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 编辑角色
const editRole = (role) => {
  isEditMode.value = true
  Object.assign(editingRole, {
    id: role.id,
    name: role.name || '',
    code: role.code || '',
    description: role.description || '',
    status: role.status
  })
  showEditModal.value = true
}

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditModal.value = false
  resetEditingRole()
}

// 关闭权限弹窗
const closePermissionModal = () => {
  showPermissionModal.value = false
  currentRole.value = null
  selectedPermissions.value = []
}

// 保存角色
const saveRole = async () => {
  if (!editingRole.name) {
    uni.showToast({
      title: '请输入角色名称',
      icon: 'none'
    })
    return
  }
  
  if (!editingRole.code) {
    uni.showToast({
      title: '请输入角色编码',
      icon: 'none'
    })
    return
  }
  
  try {
    uni.showLoading({ title: isEditMode.value ? '更新中...' : '创建中...' })
    
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 800))
    
    if (isEditMode.value && editingRole.id) {
      // 更新角色
      const roleIndex = allRoles.value.findIndex(r => r.id === editingRole.id)
      if (roleIndex !== -1) {
        allRoles.value[roleIndex] = {
          ...allRoles.value[roleIndex],
          name: editingRole.name,
          code: editingRole.code,
          description: editingRole.description,
          status: editingRole.status,
          updateTime: new Date().toISOString()
        }
      }
    } else {
      // 创建新角色
      const newRole = {
        id: Math.max(...allRoles.value.map(r => r.id)) + 1,
        name: editingRole.name,
        code: editingRole.code,
        description: editingRole.description,
        status: editingRole.status,
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString()
      }
      allRoles.value.push(newRole)
      mockRolePermissions[newRole.id] = []
    }
    
    updateRoleStats()
    
    uni.showToast({
      title: isEditMode.value ? '角色更新成功' : '角色创建成功',
      icon: 'success'
    })
    
    closeEditModal()
  } catch (error) {
    uni.showToast({
      title: isEditMode.value ? '更新失败' : '创建失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 分页控制 - 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

// 分页控制 - 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 页面加载时执行
onMounted(async () => {
  console.log('角色管理页面加载完成')
  getStatusBarHeight()
  await fetchRoles()
})
</script>

<style>
.role-container {
  padding-bottom: 120rpx;
  background-color: #FFF9F2;
  min-height: 100vh;
}

.page-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #FFFFFF;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border-bottom: 1rpx solid #FFE6CC;
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
}

.date {
  font-size: 24rpx;
  color: #999999;
  margin-top: 6rpx;
}

.refresh-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #FFF0E0;
  border-radius: 30rpx;
}

.stats-overview {
  padding: 20rpx 30rpx;
}

.stats-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.stat-card {
  width: calc(50% - 20rpx);
  margin: 10rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 20rpx;
  background-color: #FFF0E0;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 24rpx;
  color: #666666;
  display: block;
  margin-bottom: 10rpx;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  display: block;
}

.action-bar {
  padding: 20rpx 30rpx;
  display: flex;
  align-items: center;
}

.search-box {
  flex: 1;
  height: 70rpx;
  background-color: #FFFFFF;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  border: 1rpx solid #FFE6CC;
  position: relative;
}

.search-box uni-icons {
  margin-right: 10rpx;
}

.search-box input {
  flex: 1;
  height: 70rpx;
  font-size: 28rpx;
  padding-right: 40rpx;
}

.clear-search {
  position: absolute;
  right: 20rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20rpx;
}

.filter-btn {
  height: 70rpx;
  background-color: #FFFFFF;
  border-radius: 35rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 20rpx;
  margin-left: 20rpx;
  border: 1rpx solid #FFE6CC;
}

.filter-text {
  font-size: 28rpx;
  color: #666;
  margin-left: 6rpx;
}

.add-btn {
  height: 70rpx;
  background-color: #FF8C42;
  border-radius: 35rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 30rpx;
  margin-left: 20rpx;
  color: #FFFFFF;
  font-size: 28rpx;
}

.add-btn uni-icons {
  margin-right: 10rpx;
}

.status-tabs {
  padding: 10rpx 0;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #FFE6CC;
}

.status-scroll {
  width: 100%;
  white-space: nowrap;
}

.status-list {
  padding: 0 20rpx;
  display: inline-flex;
}

.status-item {
  padding: 10rpx 30rpx;
  margin: 0 10rpx;
  font-size: 28rpx;
  color: #666666;
  background-color: #F5F5F5;
  border-radius: 30rpx;
  display: inline-block;
}

.status-active {
  background-color: #FFF0E0;
  color: #FF8C42;
  font-weight: bold;
}

.role-list {
  padding: 20rpx 30rpx;
}

.role-card {
  background-color: #FFFFFF;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  border: 1rpx solid #FFE6CC;
}

.disabled-role {
  opacity: 0.7;
}

.role-header {
  padding: 20rpx;
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid #FFE6CC;
}

.role-icon-section {
  position: relative;
  margin-right: 20rpx;
}

.role-icon-wrapper {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #FFF0E0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.disabled-badge {
  position: absolute;
  top: -5rpx;
  right: -5rpx;
  padding: 4rpx 8rpx;
  background-color: #F3F4F6;
  color: #6B7280;
  font-size: 20rpx;
  border-radius: 10rpx;
}

.role-info {
  flex: 1;
  margin-right: 20rpx;
}

.role-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
  display: block;
  margin-bottom: 6rpx;
}

.role-code {
  font-size: 24rpx;
  color: #666666;
  display: block;
  margin-bottom: 6rpx;
}

.role-description {
  font-size: 22rpx;
  color: #999999;
}

.role-status {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: bold;
}

.status-normal {
  background-color: #D1FAE5;
  color: #10B981;
}

.status-disabled {
  background-color: #FEE2E2;
  color: #EF4444;
}

.role-details {
  padding: 20rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.detail-item {
  display: flex;
  margin-bottom: 8rpx;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  font-size: 26rpx;
  color: #666666;
  width: 120rpx;
  flex-shrink: 0;
}

.detail-value {
  font-size: 26rpx;
  color: #333333;
  flex: 1;
}

.role-actions {
  display: flex;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  color: #666666;
  border-right: 1rpx solid #FFE6CC;
}

.action-btn:last-child {
  border-right: none;
}

.action-btn uni-icons {
  margin-right: 6rpx;
}

.view-btn {
  color: #FF8C42;
}

.permission-btn {
  color: #10B981;
}

.enable-btn {
  color: #10B981;
}

.disable-btn {
  color: #666666;
}

.edit-btn {
  color: #666666;
}

.loading-state {
  width: 100%;
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999999;
  margin-top: 20rpx;
}

.empty-state {
  width: 100%;
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin-bottom: 30rpx;
}

.empty-action {
  padding: 16rpx 40rpx;
  background-color: #FF8C42;
  color: #FFFFFF;
  font-size: 28rpx;
  border-radius: 40rpx;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 0;
  background-color: #FFFFFF;
  border-top: 1rpx solid #FFE6CC;
}

.pagination-btn {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 30rpx;
  font-size: 24rpx;
  color: #666666;
  margin: 0 20rpx;
}

.pagination-btn.disabled {
  opacity: 0.5;
  color: #CCCCCC;
}

.prev-btn uni-icons {
  margin-right: 6rpx;
}

.next-btn uni-icons {
  margin-left: 6rpx;
}

.pagination-info {
  font-size: 24rpx;
  color: #666666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.edit-modal, .permission-modal {
  width: 650rpx;
  max-height: 80vh;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #F0F0F0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.modal-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.form-input:disabled {
  background-color: #F5F5F5;
  color: #999999;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.status-selector {
  display: flex;
  border: 1rpx solid #DDDDDD;
  border-radius: 10rpx;
  overflow: hidden;
}

.status-option {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666666;
  background-color: #F5F5F5;
  border-right: 1rpx solid #DDDDDD;
}

.status-option:last-child {
  border-right: none;
}

.status-option.active {
  background-color: #FF8C42;
  color: #FFFFFF;
}

.permission-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.permission-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #F0F0F0;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #DDDDDD;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  background-color: #FFFFFF;
}

.permission-checkbox.checked {
  background-color: #FF8C42;
  border-color: #FF8C42;
}

.permission-info {
  flex: 1;
}

.permission-name {
  font-size: 28rpx;
  color: #333333;
  display: block;
  margin-bottom: 6rpx;
}

.permission-description {
  font-size: 24rpx;
  color: #666666;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  padding: 30rpx;
  border-top: 1rpx solid #F0F0F0;
}

.cancel-btn, .confirm-btn {
  padding: 20rpx 40rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  text-align: center;
  flex: 1;
  margin: 0 10rpx;
}

.cancel-btn {
  background-color: #F0F0F0;
  color: #666666;
}

.confirm-btn {
  background-color: #FF8C42;
  color: #FFFFFF;
}
</style>